/**
 * 保存本地文件
 */
var CourseFileKey = 'course_file_key', // 本地存储key
    CourseData = {}, // 已下载的数据
    CoursePath = ''; // 当前用户的key
// 下载队列
var DownloadingMap = [], _downloadCallback = null;
// 正在下载的
var loadingKey = null, loadingProgress = 0, loadingUrl = null;

// 初始化
function initLocalDownload() {
    CourseData = api.getPrefs({key: CourseFileKey, sync: true});
    console.log(CourseData);
    if(CourseData) {
        CourseData = JSON.parse(CourseData);
    }else {
        CourseData = {};
    }
    var custId = USER.Get('custId', true);
    if(!custId) {
        api.addEventListener({
            name: 'updateUserInfo'
        }, function () {
            CoursePath = 'course'+custId;
            Logfn(2, CoursePath+'====addEventListener')
            if(CourseData[CoursePath]) {
                // 已经初始化过了
            }else {
                CourseData[CoursePath] = {};
            }
        })
    }else {
        CoursePath = 'course'+custId;
        Logfn(2, CoursePath+'==else')
        if(CourseData[CoursePath]) {
            // 已经初始化过了
        }else {
            CourseData[CoursePath] = {};
        }
    }
}

/**
 * [menuIsDownload 目录下载状态]
 * @Author ljliu    2020-04-14
 * @param  {[type]} id  [目录ID]
 * @return {[state]}    1 排队中 -1 正在下载 null 未在当前下载
 */
function menuIsDownload(id) {
    var index = findIndexInArray(DownloadingMap, 'downloadKey', id);
    if(index != -1) {
        return index; //{state: 1};
    }else if(loadingKey == id) {
        return -1; // {state: 2, progress: loadingProgress};
    }
}

/**
 * [fileIsSave 是否保存]
 * @Author ljliu    
 * @param  {string} key    文件ID
 * @return {是否保存}        未保存：null 以保存：本地路径
 */
function fileIsSave(key) {
    console.log(JSON.stringify(CourseData)+'======'+CoursePath);
    var localPath = CourseData[CoursePath][key];
    if(localPath) {
        return localPath;
    }
    return null;
}

/**
 * [insertDownload 加入下载队列]
 * @Author ljliu      
 * @param  {[type]}   data        [下载的list数据]
 * @param  {Function} callback    [下载回调]
 *
 * callback(state, progress)
 * state 1 排队中 2 正在下载 3 下载完成
 * progress 数字类型,仅在state为2时有效
 */
function insertDownload(data, callback, downloadKey) {
    var temp = {
        func: callback,
        data: data,
        downloadKey: downloadKey
    };
    var result = menuIsDownload(downloadKey);
    Logfn(2, result+'===result');
    if(result) {
        if(result == -1) {
            _downloadCallback = callback;
            fnDownloadCallback(2, loadingProgress);
        }else {
            // 排队中
            DownloadingMap[result].func = callback;
            api.sendEvent({
                name: callback,
                extra: {
                    status: 1
                }
            });
        }
    }else if(DownloadingMap.length > 0) {
        // 加入下载队列
        DownloadingMap.push(temp);
        // 回调排队中
        console.error('排队中');
        api.sendEvent({
            name: callback,
            extra: {
                status: 1
            }
        });
    }else {
        DownloadingMap.push(temp);
        // 当前无正在下载的，开始下载
        startDownload(temp);
    }
}

function fnDownloadCallback(status, progress) {
    if(status == 3) {
        // 下载完成保存记录
        try {
            var DownloadMap = {}, DownloadCourseKey = 'download_course_id',
            userMap = {}, userLoadKey = '';
            userLoadKey = 'course_'+USER.Get('custId', true);
            // 获取已缓存的小节
            DownloadMap = api.getPrefs({key: DownloadCourseKey, sync: true});
            DownloadMap = JSON.parse(DownloadMap || '{}');
            userMap = DownloadMap[userLoadKey] || {};

            userMap[loadingKey] = new Date().getTime()+'';
            DownloadMap[userLoadKey] = userMap;
            api.setPrefs({
                key: DownloadCourseKey,
                value: JSON.stringify(DownloadMap)
            });
        }catch(e) {
            Logfn(2, '保存本地课程下载结果错误：>>>>'+e);
        }
    }
    api.sendEvent({
        name: _downloadCallback,
        extra: {
            status: status,
            progress: progress
        }
    });
}

function Logfn(type, str) {
    return;
    if(type == 1) {
        // console.log(str);
    }else {
        console.error(str + new Date().getTime());
    }
}

/**
 * 取消正在下载
 * @Author ljliu    2020-08-27T17:56:48+0800
 */
var ISCANCLEDOWNLOAD = false;
function fnCancleDownloading() {
    ISCANCLEDOWNLOAD = true;
    if(loadingUrl) {
        api.cancelDownload({
            url: loadingUrl
        });
        loadingUrl = null;
    }
    loadingKey = null;
    _downloadCallback = 'null';
    loadingProgress = 0;
    DownloadingMap.shift(0);
    if(DownloadingMap.length > 0) {
        startDownload(DownloadingMap[0]); 
    }
}

/**
 * [startDownload 开始下载]
 * @Author ljliu    
 * @param  {[type]} data   [下载的数据]
 */
function startDownload(sender) {
    _downloadCallback = sender.func; // 回调方法
    loadingKey = sender.downloadKey;
    loadingProgress = 0;
    var data = sender.data,
        keyIndex = 0; // 要下载的数据
    var list = getAllKeys(data);
    function _download(key) {
        var url = data[key];
        Logfn(1, 'loading==='+key+'==url='+url+'===keyIndex=='+keyIndex);
        loadingProgress = keyIndex/list.length;
        fnDownloadCallback(2, loadingProgress);
        if(!url || typeof url !== 'string' || url.indexOf('http') == -1) {
            // url为空时
            keyIndex ++;
            if(keyIndex >= list.length) {
                // 全部下载完成
                fnDownloadCallback(3);
                loadingKey = null;
                DownloadingMap.shift(0);
                if(DownloadingMap.length > 0) {
                    startDownload(DownloadingMap[0]); 
                }
            }else {
                // 下载下一个
                _download(list[keyIndex]);
            }
            return;
        }
        loadingUrl = url;
        var name = url.split('/');
        name = name[name.length -1];
        api.download({
            url: url,
            savePath: 'fs://'+ CoursePath +'/'+ name,
            report: false,
            cache: true,
            allowResume: true
        }, function(ret, err) {
            if(ISCANCLEDOWNLOAD && !loadingUrl) {
                ISCANCLEDOWNLOAD = false;
                api.cancelDownload({
                    url: loadingUrl
                });
                // loadingKey = null;
                // _downloadCallback = 'null';
                // loadingProgress = 0;
                // DownloadingMap.shift(0);
                // if(DownloadingMap.length > 0) {
                //     startDownload(DownloadingMap[0]); 
                // }
                return;
            }
            if (ret) {
                //下载回调
                if(ret.state == 1) {
                    // 下载成功,保存本地
                    Logfn(2, '下载完成url'+ url);
                    Logfn(1, '下载完成本地路径'+ 'fs://'+ CoursePath +'/'+ name);
                    saveDownload(key, 'fs://'+ CoursePath +'/'+ name);
                }else {
                    // console.log('下载回调'+JSON.stringify(ret));
                    if(ret.state == 2) {
                        // 下载失败
                        Logfn(2, '下载出错ret===='+JSON.stringify(ret)+'====err'+JSON.stringify(err));
                        api.cancelDownload({
                            url: url
                        });
                    }
                }
            }else {
                Logfn(1, '下载出错err===='+JSON.stringify(err));
                api.cancelDownload({
                    url: url
                });
            }
            if((ret && (ret.state == 1 || ret.state == 2)) || !ret) {
                keyIndex ++;
                loadingUrl = null;
                Logfn(2, '一个下载完成=='+url+'=='+ new Date().getTime());
                if(keyIndex >= list.length) {
                    // 全部下载完成
                    fnDownloadCallback(3);
                    loadingKey = null;
                    DownloadingMap.shift(0);
                    if(DownloadingMap.length > 0) {
                        startDownload(DownloadingMap[0]); 
                    }
                }else {
                    // 下载下一个
                    _download(list[keyIndex]);
                }
            }
        });
    }
    _download(list[keyIndex]);
}

/**
 * [saveFileById 保存录音文件]
 * @Author ljliu    
 * @param  {[type]} id        [文件ID]
 * @param  {[type]} path      [文件路径]
 */
function saveDownload(id, path) {
    var userFolder = CourseData[CoursePath];
    userFolder[id] = path+'';
    var localData = JSON.stringify(CourseData);
    Logfn(1, '缓存已下载:=====>'+localData);
    api.setPrefs({
        key: CourseFileKey,
        value: localData
    });
}

function clearDownload() {
    api.setPrefs({
        key: CourseFileKey,
        value: ''
    });
}


// 获取所有文件的key
function getAllKeys(sender) {
    var result = [];
    for(var key in sender) {
        result.push(key+'');
    }
    return result;
}